﻿using System;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Context;
using Yala.Client.Web.MVC.IocSetup;
using Environment = NHibernate.Cfg.Environment;

namespace Yala.Client.Web.MVC {
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication {

        public static ISessionFactory SessionFactory = CreateSessionFactory();
        public MvcApplication() {
            BeginRequest += MvcApplication_BeginRequest;
            EndRequest += MvcApplication_EndRequest;
        }

        public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes) {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Home", action = "Index", id = UrlParameter.Optional} // Parameter defaults
                );
        }

        #region Private Methods

        private static ISessionFactory CreateSessionFactory() {
            var cfg = new Configuration().Configure();
            cfg.SetProperty(Environment.ConnectionStringName, System.Environment.MachineName);
            return cfg.BuildSessionFactory();
        }

        #endregion

        #region Events

        protected void Application_Start() {
            AreaRegistration.RegisterAllAreas();
            DependencyResolver.SetResolver(new StructureMapDependencyResolver(Bootstrapper.ConfigureStructureMap()));
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        private void MvcApplication_BeginRequest(object sender, EventArgs e) {
            CurrentSessionContext.Bind(SessionFactory.OpenSession());
        }

        private void MvcApplication_EndRequest(object sender, EventArgs e) {
            CurrentSessionContext.Unbind(SessionFactory).Dispose();
        }

        protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpCookie formsCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (formsCookie == null) return;

            FormsAuthenticationTicket auth = FormsAuthentication.Decrypt(formsCookie.Value);

            Guid userID = new Guid(auth.UserData);

            var principal = new CustomPrincipal(new GenericIdentity(auth.Name), userID);

            Context.User = Thread.CurrentPrincipal = principal;
        }


        #endregion
    }
}